package com.senjoeson.socialsecure.base;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.senjoeson.socialsecure.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public abstract class BaseActivity extends AppCompatActivity {


    private static final String TAG = "BaseActivity";
    @BindView(R.id.toolbar)
    @Nullable
    Toolbar mToolbar;
    public Unbinder mUnbinder;
    public TextView mToolBarTitle;


    private static final int REQUEST_PERMISSION_SETTING = 0x01;
    private static final int MY_PERMISSION_REQUEST_CODE = 0x02;
    public AlertDialog mAlertDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setResId());
        Log.d(TAG, "onCreate: ");
        mUnbinder = ButterKnife.bind(this);
        setToolBar();
        if (mToolbar != null) {
            String title = getIntent().getStringExtra("title") + "";
            mToolBarTitle = mToolbar.findViewById(R.id.toolbar_title);
            mToolBarTitle.setText(title);
        }

        initView();

        initListener();
    }

    protected abstract int setResId();

    /**
     * 设置toolbar中间文字的标题
     *
     * @param title 中间的文字
     */
    protected void setToolBarTitle(String title) {
        mToolBarTitle.setText(title == null ? "" : title);
    }

    /**
     * 初始化数据
     */
    protected abstract void initView();

    protected abstract void initListener();

    protected void setToolBar() {
        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
        }
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }

    private void setVisiableArrow(boolean visiable) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(visiable);
        }
    }

    private List<String> unCheckPermissions = new ArrayList<>();
    private String[] permissions;
    private String permissionsIndication;

    public void requestPermissionsEntrance(String[] permissions, String permissionsIndication) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (permissions == null) {
                Toast.makeText(this, "请求的权限不可为空", Toast.LENGTH_SHORT).show();
            } else {
                this.permissions = permissions;
                this.permissionsIndication = permissionsIndication;
                realRequestPermisionFunction(permissions);
            }
        } else {
            isHaveAllPermission = true;
            hasPermissionCallNextOperation();
        }
    }


    /**
     * 是否有被拒绝询问的权限
     */
    private boolean isHaveDeniedPermision;

    /**
     * 细致的请求权限操作：
     * 每次来请求，先应该判断是否每个权限都已经被获取。
     * 如果没有就把没有请求的权限保存在一个集合中.如果每个权限都已经获取,就可以直接执行hasPermissionCallNextOperation()方法 跳出
     * 拿到没有通过的权限，去判断一下是否已经被禁止询问， 如果被禁止询问，直接就去应用的设置中手动打开权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    public void realRequestPermisionFunction(String[] permissions) {
        //第一步，把没有请求的权限存在一个集合中
        for (String permission : permissions) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                unCheckPermissions.add(permission);
            }
        }
        if (unCheckPermissions.size() != 0) {   //如果集合不为空，意味着有权限没有被申请
            for (String permission : permissions) {
                if (shouldShowRequestPermissionRationale(permission)) {
                    isHaveDeniedPermision = true;
                    break;
                }
            }
        } else {
            isHaveAllPermission = true;
            hasPermissionCallNextOperation();
        }
        if (!isHaveAllPermission) {
            if (isHaveDeniedPermision) {      //如果有被权限拒绝询问的权限，就必须去应用设置中手动打开
                goSettingsOpenPermission(permissionsIndication);
            } else {
                requestPermissions(permissions, MY_PERMISSION_REQUEST_CODE);
            }
        }

    }


    private int deniedPermisionTime;        //被拒绝的次数
    private boolean isHaveAllPermission;   //是否已经获取了所有的权限

    /**
     * 最后一步: 申请权限结果返回处理
     * 权限申请可能会被拒绝，也可能会被通过，所以都要考虑到。
     * 如果都被拒绝询问，这个时候我们又拿不到回调， 只能通过计数，达到四次我们就直接跳转到应用设置去手动打开权限。
     */
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            // 判断是否所有的权限都已经授予了
            if (checkPermissionAllGranted(permissions)) {
                isHaveAllPermission = true;
                hasPermissionCallNextOperation();
            } else {
                if (deniedPermisionTime < 4 && !checkPermissionAllGranted(permissions)) {
                    requestPermissions(list2String(unCheckPermissions), MY_PERMISSION_REQUEST_CODE);
                    deniedPermisionTime++;
                } else {
                    goSettingsOpenPermission(permissionsIndication);
                }
            }

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    /**
     * 把保存未申请的权限转化成权限数据，
     *
     * @param unCheckPermissions 为保存的权限
     * @return 权限数组
     */
    private String[] list2String(List<String> unCheckPermissions) {
        return unCheckPermissions.toArray(new String[unCheckPermissions.size()]);
        /*if (!unCheckPermissions.isEmpty()) {
            String[] strings = new String[unCheckPermissions.size()];
            for (int i = 0; i < unCheckPermissions.size(); i++) {
                strings[i] = unCheckPermissions.get(i);
            }
            return strings;
        }
        return new String[]{};*/
    }


    /**
     * 已经获取到权限，可以进行下一步操作。
     * 仅仅在请求权限之后生效，其他时间调用无效。
     * 如果请求权限操作是在Splash界面可以跳转到主界面的操作等
     */
    protected  void hasPermissionCallNextOperation() {

    }

    /**
     * 检查是否拥有指定@param permissions的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        unCheckPermissions.clear();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                unCheckPermissions.add(permission);
                return false;
            }
        }
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 点击跳转到设置的提示对话框，
     *
     * @param forUserNotice 获取权限的提示语，
     */
    public void goSettingsOpenPermission(String forUserNotice) {
        if(mAlertDialog!=null&&mAlertDialog.isShowing()){
            return;
        }
        mAlertDialog = new AlertDialog.Builder(this)
                .setMessage(forUserNotice)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                        startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                    }
                }).show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PERMISSION_SETTING) {
            boolean checkPermissionAllGranted = checkPermissionAllGranted(permissions);
            if (checkPermissionAllGranted) {
                isHaveAllPermission = true;
                hasPermissionCallNextOperation();
            } else {
                finish();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mUnbinder!=null){
            mUnbinder.unbind();
        }
        if(mAlertDialog!=null){
            mAlertDialog.dismiss();
        }
    }
}
